package com.wondersgroup.wuhan_demo.ui.fk;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wondersgroup.wuhan_demo.Constant;
import com.wondersgroup.wuhan_demo.R;
import com.wondersgroup.wuhan_demo.base.BaseActivity;
import com.wondersgroup.wuhan_demo.net.MyCallbackBean;
import com.wondersgroup.wuhan_demo.net.OkHttpHelper;
import com.wondersgroup.wuhan_demo.net.Param;
import com.wondersgroup.wuhan_demo.util.BitmapUtil;
import com.wondersgroup.wuhan_demo.util.DataUtil;
import com.wondersgroup.wuhan_demo.util.FileUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.dom4j.Element;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.mrobot.core.log.LogUtils;
import cn.mrobot.pkgcore.cookyplus.idcard.bean.IdCardInfo;
import cn.mrobot.pkgcore.cookyplus.printer.MThermalPrinter;
import cn.mrobot.pkgcore.cookyplus.printer.TPrinterState;
import cn.mrobot.pkgcore.cookyplus.printer.builder.Line;
import cn.mrobot.pkgcore.cookyplus.printer.builder.MThermalPrinterBuilder;
import cn.mrobot.pkgcore.cookyplus.printer.listener.PrinterListener;
import cn.mrobot.pkgcore.cookyplus.printer.printer.MGpThermalPrinter;
import cn.mrobot.pkgcore.core.ErrorCode;
import okhttp3.Call;
import okhttp3.MediaType;

//import cn.mrobot.pkgcore.cookyplus.printertemplate.IPrintReader;
//import cn.mrobot.pkgcore.cookyplus.printertemplate.ThermalPrintReader;

public class OfferCardActivity extends BaseActivity implements PrinterListener {

    @BindView(R.id.tv_result)
    TextView tvResult;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.btnBack)
    Button btnBack;
    private String TAG = this.getClass().getSimpleName();
    IdCardInfo mIdCardInfo;
//    private String orgCode = "31000013";
//    private String userName = "31000013";
//    private String passWord = "1234abcd_";
//    private String orgCode = "441355122";
//    private String userName = "441355122";
//    private String passWord = "123456a_";
    private MThermalPrinter mTPrinter;
    //    private IPrintReader mPrintReader = null;
    private static final String XML_NAME = "print_template.xml";
    private boolean offerSucc=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offer_card);
        ButterKnife.bind(this);
//        mIdCardInfo = (IdCardInfo) getIntent().getSerializableExtra(ScanIDCardActivity.idCard);

        Bundle bundle=getIntent().getExtras();
        mIdCardInfo=(IdCardInfo) bundle.getSerializable(ScanIDCardActivity.idCard);
        tvResult.setText("发卡中请等待。。。");
        boolean analyze=FileUtil.analyzeFile(this);
        if (analyze) {
            getAuthKey(Constant.orgCode, Constant.userName, Constant.passWord);
        }
        initPrint();
    }

    private void getAuthKey(final String orgCodeStr, String userName, String passWord) {
        Vector v = new Vector<Param>();
        v.add(new Param("orgCode", orgCodeStr));
        v.add(new Param("userName", userName));
        v.add(new Param("passWord", passWord));
        TAG = TAG;
        OkHttpUtils.postString()
                .url(Constant.URL)
                .tag(TAG)
                .headers(OkHttpHelper.getHeaders())
                .mediaType(MediaType.parse("text/xml;charset=UTF-8"))
                .content(OkHttpHelper.requestContent(v, "getAuthKey"))
                .build()
                .execute(new MyCallbackBean<Element>() {
                    @Override
                    public void onError(Call call, Exception e) {
                        e.printStackTrace();
//                        toast("获取AuthKey失败！");
                        tvResult.setText("发卡失败！");
                    }

                    @Override
                    public void onResponse(Element response) {
                        if (response != null) {
                            String message = response.element("message").getText();
                            String resultCode = response.element("resultCode").getText();
                            if ("10000".equals(resultCode)) {
                                String authKey = response.element("authKey").getText();
                                Log.i("authKey", authKey);
//                                syncCardInfo(orgCodeStr, authKey, "5", mIdCardInfo.getCardId());
                                Log.i("idcard", mIdCardInfo.getCardId());
                                String xb = "0";
                                if ("男".equals(mIdCardInfo.getSex())) {
                                    xb = "1";
                                } else if ("女".equals(mIdCardInfo.getSex())) {
                                    xb = "2";
                                }
                                syncCardInfo(orgCodeStr, authKey, DataUtil.ConverToString(new Date(), "yyyyMMdd"), mIdCardInfo.getCardId(), mIdCardInfo.getName(), xb);
                            } else {
//                                tvResult.setText("发卡失败！");
                                Toast.makeText(getApplicationContext(), message + "", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }
                });
    }

    private void syncCardInfo(String orgCode, String authKey, String fksj, String sfzhm, String xm, String xb) {
        String v = "    <orgCode>" + orgCode + "</orgCode>\n" +
                "         <authKey>" + authKey + "</authKey>\n" +
                "         <cardInfo>\n" +
                "            <isRealName>0</isRealName>\n" +
                "            <fksj>" + fksj + "</fksj>\n" +
                "            <klx>3</klx>\n" +
                "            <orgCode>"+orgCode+"</orgCode>\n" +
                "            <yycsdm>420101</yycsdm>\n" +
                "            <issuingMode>2</issuingMode>\n" +
                "            <bankCode/>\n" +
                "            <peopleInfo>\n" +
                "               <zjlx>01</zjlx>\n" +
                "               <zjhm>" + sfzhm + "</zjhm>\n" +
                "               <sfzhm>" + sfzhm + "</sfzhm>\n" +
                "               <xm>" + xm + "</xm>\n" +
                "               <xb>" + xb + "</xb>\n" +
                "            </peopleInfo>\n" +
                "         </cardInfo>\n";
        OkHttpUtils.postString()
                .url(Constant.URL)
                .tag(TAG)
                .headers(OkHttpHelper.getHeaders())
                .mediaType(MediaType.parse("text/xml;charset=UTF-8"))
                .content(OkHttpHelper.requestContent(v, "syncCardInfo"))
                .build()
                .execute(new MyCallbackBean<Element>() {
                    @Override
                    public void onError(Call call, Exception e) {
                        e.printStackTrace();
                        tvResult.setText("点击屏幕重试！");
                    }

                    @Override
                    public void onResponse(Element response) {
                        if (response != null) {
                            String message = response.element("message").getText();
                            String resultCode = response.element("resultCode").getText();
                            if ("10000".equals(resultCode)) {
                                try {
                                    tvResult.setText("发卡成功！请取走您的二维码！");
                                    offerSucc=true;
                                    JSONObject jsonObject = new JSONObject(message);
                                    String bitmapStr = jsonObject.getString("img");
                                    Log.i("bitmapStr", bitmapStr);
                                    Bitmap bitmap = BitmapUtil.base64ToBitmap(bitmapStr);
                                    Log.i("bitmap", bitmap.toString());
                                    printTest(bitmap);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    tvResult.setText("发卡失败！点击屏幕重试");
                                }


                            } else {
                                tvResult.setText("发卡失败！点击屏幕重试");
                                Toast.makeText(getApplicationContext(), message + "", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }
                });
    }

    private void initPrint() {
        mTPrinter = MGpThermalPrinter.get();
        mTPrinter.init(getApplicationContext());
        mTPrinter.open();
        mTPrinter.registerListener(this);
//        try {
//            mPrintReader = new ThermalPrintReader(getApplicationContext(), XML_NAME);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTPrinter.unregisterListener(this);
        mTPrinter.close();
    }

    public void printTest(Bitmap bitmap) {
        mTPrinter.printBuilder(new MThermalPrinterBuilder().newLine(new Line().center().doubleSize()));
        mTPrinter.printBitmap(bitmap, 400);
        mTPrinter.printBuilder(getPrinterBuilder());
        //直接切纸
//        mTPrinter.cut();
    }

    private MThermalPrinterBuilder getPrinterBuilder() {
        return new MThermalPrinterBuilder().newLine(
                new Line().bold().center().doubleSize().fontA()).newLine()
                .newLine(new Line().center().notUnderline().content("电子健康卡")).newLine()
                .newLine(new Line().normalSize().center().notUnderline().content("打印日期：" + DataUtil.ConverToString(new Date()))).newLine()
                .newLine(new Line().center().notUnderline().content("请妥善保管好您的发卡二维码凭条")).newLine(3)
                .newLine(new Line().cutPaper());
    }

    @Override
    public void onStateChanged(final boolean connected, final TPrinterState stateCode) {
        LogUtils.d(TAG, "connected = " + connected + ", stateCode = " + stateCode);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                Toast.makeText(getApplicationContext(),
//                        "connected = " + connected + ", stateCode = " + stateCode,
//                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onPrintError(final ErrorCode error) {
        Log.i(TAG, "ErrorCode = " + error.getCode() + ", message = " + error.getMessage());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                Toast.makeText(getApplicationContext(),
//                        "ErrorCode = " + error.getCode() + ", message = " + error.getMessage(),
//                        Toast.LENGTH_SHORT).show();
            }
        });
    }


    @OnClick({R.id.ll, R.id.btnBack})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll:
                boolean analyze=FileUtil.analyzeFile(this);
                if (analyze&&!offerSucc) {
                    getAuthKey(Constant.orgCode, Constant.userName, Constant.passWord);
                }
                break;
            case R.id.btnBack:
                finish();
                break;
        }
    }

}
